package mo.leetcode_hot;

import mo.common.TreeNode;

import java.util.Arrays;

public class L105 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0 || inorder.length == 0) {
            return null;
        }
        int val = preorder[0];
        TreeNode root = new TreeNode(val);
        int leftLength = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == val) {
                leftLength = i;
                break;
            }
        }
        root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1+leftLength), Arrays.copyOfRange(inorder,0, leftLength));
        root.right = buildTree(Arrays.copyOfRange(preorder, leftLength+1, preorder.length), Arrays.copyOfRange(inorder, leftLength+1, inorder.length));
        return root;
    }

}
